package com.ktjy.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ktjy.entity.SysRight;
import com.ktjy.service.ISysRightService;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lqm
 * @ClassName ShiroConfig
 * @description: shiro对象配置类
 */
@Configuration
public class ShiroConfig {


    @Resource
    ISysRightService sysRightService;

    /**
     * 配置自定义验证数据源
     *
     * @return
     */
    @Bean
    public Realm getRealm() {
        return new CutomerRealm();
    }

    /**
     * 配置安全管理器并将验证数据源注入
     *
     * @return
     */
    @Bean(name = "securityManager")
    public SecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(getRealm());
        return manager;
    }

    /**
     * shiro 过滤器
     *
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //登录路径
        shiroFilterFactoryBean.setLoginUrl("/");
        //成功路径
        shiroFilterFactoryBean.setSuccessUrl("/mian");
        //授权失败路径
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        //鉴权处理
        Map<String,String> staticeMap=new LinkedHashMap<>();
        staticeMap.put("/static/**","anon");
        staticeMap.put("/css/**","anon");
        staticeMap.put("/403","anon");
        staticeMap.put("/doLogin","anon");
        staticeMap.put("/mian","anon");

        //添加所有需要权限验证的资源到过滤器规则中
        List<SysRight> rightList=sysRightService.list();
        for (SysRight temp:rightList) {

            if(StringUtils.isNotEmpty(temp.getRightUrl().trim())){
                staticeMap.put(temp.getRightUrl(),"perms["+temp.getRightCode()+"]");
            }
        }

        //配置认证访问：其他资源(URL)必须认证通过才能访问
        staticeMap.put("/**","authc"); //必须放在过滤器链的最后面

        shiroFilterFactoryBean.setFilterChainDefinitionMap(staticeMap);


        return shiroFilterFactoryBean;
    }


}
